package doing.doing_001_500;

import org.junit.Test;

import static com.study.util.LogUtil.info;

/**
 * 303. Range Sum Query - Immutable 区域和检索 - 数组不可变
 * <p>
 * 给定一个整数数组  nums，求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和，包含 i,  j 两点。
 * <p>
 * 示例：
 * 给定 nums = [-2, 0, 3, -5, 2, -1]，求和函数为 sumRange()
 * 说明:
 * <p>
 * 你可以假设数组不可变。
 * 会多次调用 sumRange 方法。
 *
 * @author 大硕
 * 2019-04-14 10:22 AM
 **/
@SuppressWarnings("all")
public class RangeSumQuery_Immutable {

    class NumArray {

        private int[] sums;

        public NumArray(int[] nums) {
            sums = new int[nums.length];
            if (nums.length == 0) {
                return;
            }
            sums[0] = nums[0];
            for (int i = 1; i < nums.length; i++) {
                sums[i] += sums[i - 1] + nums[i];
            }
        }

        public int sumRange(int i, int j) {
            if (i == 0) {
                return sums[j];
            } else {
                return sums[j] - sums[i - 1];
            }
        }
    }

    @Test
    public void test() {
        NumArray na = new NumArray(new int[]{-2, 0, 3, -5, 2, -1});
        info(" 1 ->  {}", na.sumRange(0, 2));
        info("-1 -> {}", na.sumRange(2, 5));
        info("-3 -> {}", na.sumRange(0, 5));
    }
}


























/*
class NumArray {

    private int[] sums;

    public NumArray(int[] nums) {
        sums = new int[nums.length];
        if (nums.length == 0) {
            return;
        }
        sums[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sums[i] += sums[i - 1] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        if (i == 0) {
            return sums[j];
        } else {
            return sums[j] - sums[i - 1];
        }
    }
}
*/
